package org.example.seatunnel;

import com.typesafe.config.Config;
import org.example.SqlTablePrefixer;
import org.example.datasource.DataSourceApi;
import org.example.datasource.impl.DataLinkMedataDataSourceImpl;
import org.example.datasource.model.JdbcDataSourceInfo;
import org.example.datasource.model.TableMetadata;
import org.example.seatunnel.model.SourceResModel;

import java.util.List;

public class SeatunnelJdbcSource implements SeatunnelSource{


    @Override
    public SourceResModel parse(Config config) {
        if (config.hasPath("Jdbc")){
            config = config.getConfig("Jdbc");
        }
        if (config.hasPath("jdbc")){
            config = config.getConfig("jdbc");

        }
        JdbcDataSourceInfo jdbcDataSourceInfo = new JdbcDataSourceInfo();
        jdbcDataSourceInfo.setUrl(config.getString("url"));
        jdbcDataSourceInfo.setPassword(config.getString("password"));
        jdbcDataSourceInfo.setUsername(config.getString("user"));


        if (config.hasPath("query")){

//            System.out.println(config.getString("query"));
            String query = config.getString("query");
            query = query.replaceAll("\\[","");
            query = query.replaceAll("]","");
            query = query.replaceAll("`","");

            DataSourceApi dataSourceApi = new DataLinkMedataDataSourceImpl(jdbcDataSourceInfo);
            List<TableMetadata> tableMetadataList =  dataSourceApi.getTableMetadata(query,false);
            SourceResModel sourceResModel = new SourceResModel();
            sourceResModel.setConfig(config);
            sourceResModel.setSql(query);
            sourceResModel.setTableMetadataList(tableMetadataList);

            return sourceResModel;
        }else {
            System.out.println(config);
        }
        return null;
    }

    @Override
    public boolean isSupport(Config config) {
        if (config.hasPath("Jdbc")){
            return true;
        }
        if (config.hasPath("jdbc")){
            return true;
        }
        return false;
    }
}
